package com.outfood.task;

import com.alibaba.fastjson.JSON;
import com.outfood.common.eleme.evaluate.ElemEvaluate;
import com.outfood.domain.ElemeEvaluateRecord;
import com.outfood.domain.EvaluateRecord;
import com.outfood.domain.Store;
import com.outfood.service.IElemeEvaluateRecordService;
import com.outfood.service.IEvaluateRecordSerivice;
import com.outfood.service.IStoreService;
import com.outfood.service.impl.ElmeOperateServiceImpl;
import com.outfood.service.impl.MeiTuanOperateServiceImpl;
import com.ruoyi.common.exception.BusinessException;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.Search;
import lombok.extern.log4j.Log4j2;
import okhttp3.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.task
 * @Date 2024-05-08 16:53
 * @Version 1.0
 */
@Log4j2
//@Component
public class ElemeEvaluateTask {


    @Resource
    ElmeOperateServiceImpl elmeOperateService;

    @Resource
    IStoreService storeService;

    @Resource
    IElemeEvaluateRecordService elemeEvaluateRecordService;

    @Scheduled(cron = "0 4 */1 * * ?")
    public void scanEvaluate() {
        long start = new Date().getTime();
        log.info("--------------------------------------------开始门店评价信息------------------------------------------------------------");
        List<Store> storeList = storeService.getList(new Search().add("storeStatus", SearchTypeEnum.EqualTo, "1").add("platform","ELEME").add("onlineStatus", SearchTypeEnum.EqualTo, "ONLINE"));
        storeList.forEach(store -> {
            try {
                MeiTuanOperateServiceImpl.QueryEvaluate queryEvaluate = new MeiTuanOperateServiceImpl.QueryEvaluate();
                queryEvaluate.setStoreId(store.getId());
                elmeOperateService.getEvaluateList(store.getId());
            } catch (Exception e) {
                log.error("获取饿了么评价列表失败");
            }
        });
        long end = new Date().getTime();
        log.info("--------------------------------------------门店评价获取结束 总耗时{}ms------------------------------------------------------------", start - end);
    }



    @Scheduled(cron = "0 9 */1 * * ?")
    public void scanNotEvaluate() {
        long start = new Date().getTime();
        log.info("--------------------------------------------开始对用户的评价进行回复------------------------------------------------------------");
        List<ElemeEvaluateRecord> list = elemeEvaluateRecordService.getList(new Search().add("replayResult", SearchTypeEnum.EqualTo, "NOT"));
        list.forEach(evaluateRecord -> {
            try {
                Store store = storeService.get(evaluateRecord.getStoreId());
                if("TRUE".equals(store.getAutoReplay())){ //开启自动回复
                    elmeOperateService.replay(evaluateRecord.getId(), getComment(evaluateRecord));
                }else{
                    log.info("该门店没有开启自动回复");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        long end = new Date().getTime();
        log.info("--------------------------------------------对用户的评价进行回复结束耗时{}ms------------------------------------------------------------", start - end);
    }


    @Resource
    RedisTemplate redisTemplate;
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    //通过人工智能进行回复
    public  String getComment(ElemeEvaluateRecord evaluateRecord) throws IOException {
        Boolean isRepayed = redisTemplate.opsForValue().setIfAbsent("vid:"+evaluateRecord.getId()+"", "1", 90, TimeUnit.DAYS);
        if(isRepayed){

            String prompt = "你是一个外卖商家 规则是 星级共5星 用户给的是"+evaluateRecord.getOrderCommentScore()+"星 总分是5分 " +
                    "用户给的是" + evaluateRecord.getOrderCommentScore() + "分，口味总分是5分 用户给的是" + evaluateRecord.getTasteScore() + "分，包装总分是5分用户给的是" + evaluateRecord.getPackagingScore() + "分 " +
                    "用户点的餐是： " + evaluateRecord.getFoodName() + "" +
                    "用户的评价为：   " + evaluateRecord.getComment() + "   请综合以上以外卖商家的身份给用户一个满意的口头回复不要携带XXX等字符 要求在50个字以内";
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"messages\":[{\"role\":\"user\",\"content\":\"" + prompt + "\"}],\"stream\":false}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + EvaluateTask.getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = response.body().string();
            String result = JSON.parseObject(string).getString("result");
            log.info(result);
            return result;

        }
        throw  new BusinessException("该评论已进行过回复");

    }
}
